import dayjs from 'dayjs'
import { date } from '../filters'

export const dayTimeStamp = 24 * 60 * 60 * 1000
export const now = dayjs().toDate()
export const twoDaysAgo = dayjs()
  .subtract(2, 'd')
  .startOf('day')
  .toDate()
export const weekAgo = dayjs()
  .subtract(6, 'd')
  .startOf('day')
  .toDate()
export const monthAgo = dayjs()
  .subtract(1, 'M')
  .startOf('day')
  .toDate()
export const quarterAgo = dayjs()
  .subtract(3, 'M')
  .startOf('day')
  .toDate()
export const halfAYearAgo = dayjs()
  .subtract(6, 'M')
  .startOf('day')
  .toDate()
export const oneYearAgo = dayjs()
  .subtract(12, 'M')
  .startOf('day')
  .toDate()

export const shortcuts = [
  {
    text: '三天内',
    value () {
      return [twoDaysAgo, now]
    }
  },
  {
    text: '七天内',
    value () {
      return [weekAgo, now]
    }
  },
  {
    text: '一个月内',
    value () {
      return [monthAgo, now]
    }
  }
]

/**
 * 生成快捷时间选择组件
 * @param {['day', 'week', 'month', 'quarter', 'halfAYear', 'year']} range 时间选项
 */
export const generateShortcuts = (range = ['day', 'week', 'month']) => {
  const result = []
  if (range.includes('day')) {
    result.push({
      text: '三天内',
      value () {
        return [twoDaysAgo, now]
      }
    })
  }
  if (range.includes('week')) {
    result.push({
      text: '七天内',
      value () {
        return [weekAgo, now]
      }
    })
  }
  if (range.includes('month')) {
    result.push({
      text: '一个月内',
      value () {
        return [monthAgo, now]
      }
    })
  }
  if (range.includes('quarter')) {
    result.push({
      text: '三个月内',
      value () {
        return [quarterAgo, now]
      }
    })
  }
  if (range.includes('halfAYear')) {
    result.push({
      text: '半年',
      value () {
        return [halfAYearAgo, now]
      }
    })
  }
  if (range.includes('year')) {
    result.push({
      text: '一年内',
      value () {
        return [oneYearAgo, now]
      }
    })
  }
  return result
}

export const startOfDay = (time, timestamp = true) => {
  if (!time) return null
  const result = dayjs(time).startOf('day')
  return timestamp ? result.valueOf() : result
}

export const endOfDay = (time, timestamp = true) => {
  if (!time) return null
  const result = dayjs(time).endOf('day')
  return timestamp ? result.valueOf() : result
}

export const searchTimeRange = times => {
  return [ startOfDay(times[0]), endOfDay(times[1]) ]
}

/** 判断时间差 */
export const timeRangeDifference = (start_time, end_time, day) => {
  if (!start_time || !end_time) return true
  const timeDiff = day * 24 * 60 * 60 * 1000
  if (end_time - start_time > timeDiff) {
    return true
  }
  return false
}

export { dayjs, date }
